#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2019/12/12 11:53|11:53
# @Author  : yangdingyi
# @File    : 快乐数
# @Software: PyCharm


class Solution:
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        # def work(n):
        #     ans = 0
        #     while n > 0:
        #         p = n % 10
        #         ans += p * p
        #         n //= 10
        #     return ans
        #
        # m = {n: 1}
        # while n != 1:
        #     n = work(n)
        #     if m.get(n):
        #         break
        #     else:
        #         m[n] = 1
        #
        # return n == 1
        def cal(num: int) -> int:
            ans = 0
            while num:
                ans += (num % 10) ** 2
                num //= 10
            return ans
        n_set = set()
        while n != 1:
            n_set.add(n)
            n = cal(n)
            if n in n_set:
                break
        return n == 1


